package com.area.cth.controller;

import com.area.cth.mapper.UserMapper;
import com.area.cth.common.PageBean;
import com.area.cth.common.Result;
import com.area.cth.pojo.User;
import com.area.cth.service.UserService;
import com.area.cth.utils.JwtUtil;
import com.area.cth.utils.Md5Util;
import com.area.cth.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Tag(name = "用户相关接口")
@RestController
@RequestMapping("/user")
@Validated
@CrossOrigin
public class UserController {
    @Autowired
    private UserService us;
    @Autowired
    private StringRedisTemplate srt;
    @Autowired
    private UserMapper userMapper;

    @Operation(summary = "注册")
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{8,24}$") String username, @Pattern(regexp = "^\\S{8,32}$") String password) {
        User u = us.findByUsername(username);
        if (u == null) {
            us.register(username, password);
            return new Result(0,"注册成功",null);
        } else {
            return Result.error("用户名已被占用");
        }
    }

    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{8,24}$") String username, @Pattern(regexp = "^\\S{8,32}$") String password) {
        User lu = us.findByUsername(username);
        if (lu == null) {
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(password).equals(lu.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", lu.getId());
            claims.put("username", lu.getUsername());
            String token = JwtUtil.genToken(claims);

            ValueOperations<String, String> operations = srt.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);

            us.login(username);
            return new Result(0,"登录成功",token);
        }
        return Result.error("密码错误");
    }

    @Operation(summary = "查询个人信息")
    @GetMapping("/userInfo")
    public Result<User> getUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = us.findByUsername(username);
        return Result.success(user);
    }

    @Operation(summary = "修改个人头像")
    @PutMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatar) {
        us.updateAvatar(avatar);
        return new Result(0,"修改成功",null);
    }

    @Operation(summary = "修改个人背景图")
    @PutMapping("/updateBackground")
    public Result updateBackground(@RequestParam @URL String background) {
        us.updateBackground(background);
        return new Result(0,"修改成功",null);
    }

    @Operation(summary = "修改个人信息")
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        us.update(user);
        return new Result(0,"修改成功",null);
    }

    @Operation(summary = "修改密码")
    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        String oldPwd = params.get("oldPassword");
        String newPwd = params.get("newPassword");
        String rePwd = params.get("rePassword");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User lU = us.findByUsername(username);
        if (!lU.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码填写不正确");
        }

        if (!rePwd.equals(newPwd)) {
            return Result.error("两次填写的密码不一致");
        }

        if (newPwd.length() < 8 || newPwd.length() > 32) {
            return Result.error("新密码格式不正确");
        }

        if (lU.getPassword().equals(Md5Util.getMD5String(newPwd))) {
            return Result.error("新密码不能与原密码一致");
        }

        us.updatePwd(newPwd);
        ValueOperations<String, String> operations = srt.opsForValue();
        operations.getOperations().delete(token);
        return new Result(0,"修改成功",null);
    }

    @Operation(summary = "分页查询")
    @GetMapping("/userList")
    public Result<PageBean<User>> getUserList(Integer pageNo, Integer pageSize, @RequestParam(required = false) String keyword) {
        PageBean<User> pb = us.getUsers(pageNo, pageSize, keyword);
        return Result.success(pb);
    }

    @Operation(summary = "根据id查询用户")
    @GetMapping("/getUserInfoById")
    public Result<User> getUserInfoById(Integer id) {
        User user = us.getUserInfoById(id);
        return Result.success(user);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping
    public Result delete(Integer id) {
        userMapper.deleteById(id);
        return Result.success();
    }
}
